/// Creator:      gaoruishan
/// CreatDate:    2025-07-24
/// Description:  健康宣教
Class Nur.MNISV3.Service.Education Extends %RegisteredObject [ Not ProcedureBlock ]
{

/// 查询宣教（待宣或者已宣）列表
/// w ##class(Nur.MNISV3.Service.Education).GetEducationDataV4("","2025-07-22","2025-07-24","3","20665","8","2","23","","{""single"":"""",""tab"":"""",""multiple"":""1""}")
ClassMethod GetEducationDataV4(episodeId, fromDate, toDate, wardId, userId, locId, hospitalId, groupId, screenParts, extras) As %String
{
    n (episodeId, fromDate, toDate, wardId, userId, locId, hospitalId,groupId,screenParts, extras,%session)
    s $zt="errGetEducationDataV4"
    s ^GRS("GetEducationDataV4",episodeId_"-")=$lb(episodeId, fromDate, toDate, wardId, userId, locId, hospitalId,groupId,screenParts, extras)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()

    s tabs=##class(%ListOfDataTypes).%New()
    d tabs.Insert(##class(Nur.Tools).RapidAssembly("id,title,selected","unexecuted","待宣","1")) //selected=1默认选中
    d tabs.Insert(##class(Nur.Tools).RapidAssembly("id,title,selected","executed","已宣",""))
    
    s buttons=##class(%ListOfDataTypes).%New()
    d buttons.Insert(##class(Nur.Tools).RapidAssembly("id,text,motion","undo","撤销执行","undo"))
    d buttons.Insert(##class(Nur.Tools).RapidAssembly("id,text,motion","delete","删除","delete"))
    s slide=##class(%ArrayOfDataTypes).%New()
    d slide.SetAt(buttons,"buttons")
    
    s patInfoList=##class(%ListOfDataTypes).%New()  
    i episodeId'="" {//单患者
        s patinfo=##class(%ArrayOfDataTypes).%New()
        //基本患者信息
        s patinfo=##class(Nur.MNISV3.Service.Patient).GetBasicInfo(patinfo,episodeId)
        s educationData=..GetEducationDataObj(episodeId,fromDate,toDate, wardId, userId, locId, hospitalId,groupId,extras) 
        d patinfo.SetAt($g(educationData),"educationData")
        d patInfoList.Insert(patinfo)
    }else {
        //调用纯净版患者列表，
        s patListObj=##class(%ResultSet).%New("Nur.MNISV3.Service.Patient:GetPatList")
        d patListObj.Execute(wardId,userId,"Ward",locId)
        while(patListObj.Next()){
            s patinfo=##class(Nur.MNISV3.Common.Utils).ResultSet(patListObj)
            s episodeId=patListObj.GetDataByName("episodeId")
            s educationData=..GetEducationDataObj(episodeId,fromDate,toDate, wardId, userId, locId, hospitalId,groupId,extras) 
            d patinfo.SetAt($g(educationData),"educationData")
            //基本患者信息
            s patinfo=##class(Nur.MNISV3.Service.Patient).GetBasicInfo(patinfo,episodeId)
            d patInfoList.Insert(patinfo)
        }
    }
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(patInfoList),"patients")
    d json.SetAt($g(tabs),"tabs")
    d json.SetAt($g(slide),"slide")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetEducationDataV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 查询宣教主题配置项  
/// w ##class(Nur.MNISV3.Service.Education).GetEducationSubjectItemsV4("471","3","20665","8","2","23")
ClassMethod GetEducationSubjectItemsV4(episodeId, wardId, userId, locId, hospitalId, groupId) As %String
{
    n (episodeId,wardId, userId, locId, hospitalId,groupId,%session)
    s $zt="errGetEducationSubjectItemsV4"
    s ^GRS("GetEducationSubjectItemsV4",episodeId_"-")=$lb(episodeId,wardId, userId, locId, hospitalId,groupId)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s hospItems=##class(Nur.NIS.Service.Education2.Setting).GetEduSubjectList("",1,hospitalId,episodeId)
    s wardItems=##class(Nur.NIS.Service.Education2.Setting).GetEduSubjectList(wardId,1,hospitalId,episodeId)
    s hospNodes=..GetSubjectNodes(hospItems)
    s wardNodes=..GetSubjectNodes(wardItems)
    s list=##class(%ListOfDataTypes).%New()
    i (wardNodes.Count()>0) {
        d ..AddSubjectItem(list,"本病区",wardNodes,1)
        d ..AddSubjectItem(list,"全院",hospNodes,0)
    } else {
        d ..AddSubjectItem(list,"全院",hospNodes,1)
    }
   
   // s subjectItems=##class(Nur.Tools).RapidAssembly("subjectItems",list)
    
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status")
    d json.SetAt($g(list),"subjectItems")
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetEducationSubjectItemsV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 多个主题对应的内容配置项 
/// w ##class(Nur.MNISV3.Service.Education).GetEducationContentItemsV4("[""85""]","[]","3","20665","8","2","23")
ClassMethod GetEducationContentItemsV4(subjectIds, taskIds, wardId, userId, locId, hospitalId, groupId) As %String
{
    n (subjectIds,taskIds,wardId, userId, locId, hospitalId,groupId,%session)
    s $zt="errGetEducationContentItemsV4"
    s ^GRS("GetEducationContentItemsV4")=$lb(subjectIds,taskIds,wardId, userId, locId, hospitalId,groupId)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
   
    s contentItems=..GetContentItems(subjectIds,taskIds)
    //s MethodParam=$g(^oddCOM("Nur.NIS.Service.Education2.HealthRecord","m","GetHealthEduItemOptions",60))
    //s optionItems=##class(Nur.NIS.Service.Education2.HealthRecord).GetHealthEduItemOptions(wardId,hospitalId)
    s optionItems=##class(Nur.NIS.Service.Education2.HealthRecord).GetHealthEduItemOptions(wardId)

    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status") 
    d json.SetAt($g(optionItems),"optionItems") 
    d json.SetAt($g(contentItems),"contentItems") 
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetEducationContentItemsV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 执行宣教（新增宣教或者执行任务
/// w ##class(Nur.MNISV3.Service.Education).ExecuteEducationV4("","471","execute","{""date"":""2025-07-24"",""subjectIds"":[""85""],""contents"":[{""pid"":""0"",""eduContent"":""手腕带宣教"",""subjectId"":""85"",""taskId"":""""},{""pid"":""85"",""eduContent"":""亲爱的病友\n    在您办理入院手续后我们为您打印腕带，内容包含您的姓名，住院号，性别及年龄等等，护士将双人核对您腕带上的内容，核对无误后将为您佩戴腕带\n护士将根据您的生活习惯，疾病及局部皮肤血运等情况选择佩戴肢体\n住院期间均须佩戴腕带，请在行各种检查及治疗护理时配合医护人员出示腕带\n如腕带上的信息模糊或者腕带损坏，请告知护士给予重新打印并为您佩戴如佩戴腕带时自觉局部皮肤红痒或其他不适时应及时告知医护人员\n出院时护士会为您去除腕带\n谢谢您的配合"",""subjectId"":"""",""taskId"":""""}],""options"":[{""id"":""1"",""option"":""本人""},{""id"":""2"",""option"":""小学""},{""id"":""3"",""option"":""书写、印刷""},{""id"":""4"",""option"":""我已完全了解""},{""id"":""5"",""option"":""完全了解""}],""time"":""15:21"",""taskIds"":""[]"",""remarks"":""""}","3","20665","8","2","23")
ClassMethod ExecuteEducationV4(id, episodeId, motion, form, wardId, userId, locId, hospitalId, groupId) As %String
{
    n (id,episodeId,motion,form,wardId, userId, locId, hospitalId,groupId,%session)
    s $zt="errExecuteEducationV4"
    s ^GRS("ExecuteEducationV4",episodeId_"-")=$lb(id,episodeId,motion,form,wardId, userId, locId, hospitalId,groupId)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
    s formObj=##class(Nur.MNISV3.Common.JSON).Decode(form)
    s contents=formObj.GetAt("contents")
    s remarks=formObj.GetAt("remarks")
    s date=formObj.GetAt("date")
    s time=formObj.GetAt("time")
    s options=formObj.GetAt("options")  
    s subjectIds=formObj.GetAt("subjectIds")
    s taskIds=formObj.GetAt("taskIds")
    //转换字符串
    i $isobject(subjectIds) s subjectIds=##class(Nur.MNISV3.Common.JSON).Encode(subjectIds)
    i (motion="execute") {
        s output=##class(Nur.NIS.Education2).AddOrUpdateEducation2RecordNew(episodeId,contents,remarks,date,time,options,userId,locId,wardId,id,subjectIds,taskIds)
        i output'=0 s Status="-1",Msg=output
        i output="-1000" s Status="-1",Msg="出院病历未对此操作授权。"
    } elseif (motion="undo") {
        s output=##class(Nur.NIS.Service.Education2.Biz).CancelEducationResult(id,userId)
        i +output=0 s Status="-1",Msg=output
    } elseif (motion="delete") {
        ;;;删task不是删记录，task和记录不同，task是生成的，记录是执行了就有，对应的撤销执行
        s output=##class(Nur.NIS.Service.Education2.Biz).DeleteEducationTask(taskId)
        i +output=0 s Status="-1",Msg=output
    }
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status") 
    d json.SetAt($g(output),"output") 
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errExecuteEducationV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

/// 查询用药情况  
/// w ##class(Nur.MNISV3.Service.Education).GetEducationMedicationV4("1217","2025-07-18","2025-07-25","","3","20665","8","2")
ClassMethod GetEducationMedicationV4(episodeId, fromDate, toDate, type = "", wardId, userId, locId, hospitalId) As %String
{
    n (episodeId,fromDate,toDate,type,wardId, userId, locId, hospitalId,%session)
    s $zt="errGetEducationMedicationV4"
    s ^GRS("GetEducationMedicationV4")=$lb(episodeId,fromDate,toDate,type,wardId, userId, locId, hospitalId)
    s Msg="成功",msgcode="999999",Status="0" //定义初始值
    s json=##class(%ArrayOfDataTypes).%New()
   
    s ordersResult=##class(%ResultSet).%New("Nur.NIS.Service.Education2.Biz:GetTypeOrderInPeriod")
    d ordersResult.Execute(episodeId,fromDate,toDate,$s(type="":"R",1:type))
    s orders= ##class(Nur.MNISV3.Common.Utils).ResultSetToList(ordersResult)
   
    d json.SetAt($g(Msg),"msg")
    d json.SetAt($g(msgcode),"msgcode")
    d json.SetAt($g(Status),"status") 
    d json.SetAt($g(orders),"orders") 
    q ##class(Nur.MNISV3.Common.JSON).Encode(json)
errGetEducationMedicationV4
    s Msg=$ze
    q ##class(Nur.MNISV3.Common.Utils).ReturnMsgJson(Msg,"100021","-1")
}

ClassMethod GetContentItems(subjectIds, taskIds) As %String
{
    n (subjectIds,taskIds,%session)
    s taskList=##class(Nur.MNISV3.Common.JSON).Decode(taskIds)
    s nodes=##class(%ListOfDataTypes).%New()
    s items=##class(Nur.NIS.Service.Education2.Setting).GetEduContentsByIds(subjectIds)
    s len=items.Count()
    s maxNo=0
    f ind=1:1:len {
        s item=items.GetAt(ind)
        s subjectId=item.GetAt("subjectId")
        i (subjectId>maxNo) s maxNo=subjectId
    }
    s maxNo=$i(maxNo)
    f ind=1:1:len {
        s item=items.GetAt(ind)
        s nodeId=maxNo
        s maxNo=$i(maxNo)
        s subjectId=item.GetAt("subjectId")
        s taskId=taskList.GetAt(ind)
        s node=##class(%ArrayOfDataTypes).%New()
        d node.SetAt(nodeId,"id")
        d node.SetAt(subjectId,"subjectId")
        d node.SetAt(0,"pid")
        d node.SetAt(item.GetAt("title"),"eduContent")
        d node.SetAt(taskId,"taskId")
        d nodes.Insert(node)
        s children=##class(%ListOfDataTypes).%New()
        d node.SetAt(children,"children")
        s contents=item.GetAt("content")
        s len2=contents.Count()
        f ind2=1:1:len2 {
            s content=contents.GetAt(ind2)
            s nodesubId=maxNo
            s maxNo=$i(maxNo)
            s nodesub=##class(%ArrayOfDataTypes).%New()
            d nodesub.SetAt(nodesubId,"id")
            d nodesub.SetAt(subjectId,"pid")
            d nodesub.SetAt(nodeId,"ascii0x5FparentId")
            d nodesub.SetAt(content,"eduContent")
            d nodesub.SetAt(taskId,"taskId")
            d children.Insert(nodesub)
        }
    }
    q nodes
}

ClassMethod AddSubjectItem(list, title, nodes, selected) As %String
{
    n (list,title,nodes,selected)
    s item=##class(%ArrayOfDataTypes).%New()
    d item.SetAt(title,"title")
    d item.SetAt(nodes,"nodes")
    d item.SetAt(selected,"selected")
    d list.Insert(item)
    q $$$OK
}

ClassMethod GetSubjectNodes(items) As %String
{
    n (items)
    k nodeArr,nodesubArr
    s len=items.Count()
    f ind=1:1:len {
        s item=items.GetAt(ind)
        s pid=item.GetAt("pid")
        s id=item.GetAt("id")
        continue:(pid="")||(id="")
        s sortNo=item.GetAt("sortNo")
        i (sortNo="") s sortNo="-"
        ;;;同一个节点下排序
        i (pid=0) s nodeArr(pid,sortNo,id)=item
        e  s nodesubArr(pid,sortNo,id)=item
    }
    s nodes=##class(%ArrayOfDataTypes).%New()
    s pid1="" f  s pid1=$o(nodeArr(pid1)) q:(pid1="")  d
    .s children1=##class(%ListOfDataTypes).%New()
    .d nodes.SetAt(children1,pid1)
    .s sortNo1="" f  s sortNo1=$o(nodeArr(pid1,sortNo1)) q:(sortNo1="")  d
    ..s id1="" f  s id1=$o(nodeArr(pid1,sortNo1,id1)) q:(id1="")  d
    ...s item1=nodeArr(pid1,sortNo1,id1)
    ...d children1.Insert(item1)
    ...s children2=##class(%ListOfDataTypes).%New()
    ...s sortNo2="" f  s sortNo2=$o(nodesubArr(id1,sortNo2)) q:(sortNo2="")  d
    ....s id2="" f  s id2=$o(nodesubArr(id1,sortNo2,id2)) q:(id2="")  d
    .....s item2=nodesubArr(id1,sortNo2,id2)
    .....d children2.Insert(item2)
    ...q:(children2.Count()=0)
    ...d item1.SetAt(children2,"children")
    i ('nodes.IsDefined(0)) d nodes.SetAt(##class(%ListOfDataTypes).%New(),0)
    q nodes.GetAt(0)
}

ClassMethod GetEducationDataObj(episodeId, fromDate, toDate, wardId, userId, locId, hospitalId, groupId, extras) As %String
{
    n (episodeId,fromDate,toDate, wardId, userId, locId, hospitalId,groupId,extras,%session)
    s data=##class(%ListOfDataTypes).%New()
    s tab=##class(Nur.MNISV3.Common.JSON).Decode(extras).GetAt("tab")
    i (tab="unexecuted")||(tab="") {
        s ret=##class(Nur.NIS.Service.Education2.Biz).UpdateEduTaskAndReturnList(episodeId,wardId,userId,locId,hospitalId,"")
        q:('$isobject(ret)) data
        s dataOld=##class(Nur.MNISV3.Common.JSON).Decode(ret)
        s dataNew=##class(%ListOfDataTypes).%New()
        k contentArr
        s tempStr=""
        s len=dataOld.Count()
        f ind=1:1:len {
            s old=dataOld.GetAt(ind)
            s subjectId=old.GetAt("subjectId")
            continue:(subjectId="")
            continue:(tempStr[subjectId) //竟然有1000多重复的
            s tempStr=tempStr_"^"_subjectId
            i ('$d(contentArr(subjectId))) {
                s contentObj=##class(Nur.NIS.Service.Education2.Setting).GetEduContentsByIds("["_subjectId_"]").GetAt(1)
                s contentArr(subjectId)=contentObj
            } else {
                s contentObj=$g(contentArr(subjectId))
            }
            s obj=##class(Nur.Tools).RapidSubset("planDate^taskId",old)
            s subjects=##class(%ListOfDataTypes).%New()
            s subject=##class(Nur.Tools).RapidSubset("title^content",contentObj)
            d subjects.Insert(subject)
            s subjectIds=##class(Nur.Tools).GetOptionsAsList(subjectId,",")
            s planDate=##class(Nur.Tools).Date(old.GetAt("planDate"))
            s eduDateFlag=$s((planDate>0)&&(planDate'>+$h):"宣教到期",1:"")
            i planDate'="" s planDate=$zd(planDate,3)
            d obj.SetAt(subjects,"subjects")
            d obj.SetAt(subjectIds,"subjectIds")
            d obj.SetAt(eduDateFlag,"eduDateFlag")
            d obj.SetAt(planDate,"planDate")
            d dataNew.Insert(obj)
        }
        s data=dataNew
    } elseif (tab="executed") {
        s ret=##class(Nur.NIS.Service.Education2.Biz).GetEducationColumnAndRecordNew(episodeId,wardId,hospitalId,fromDate,toDate,"")
        q:('$isobject(ret)) data
        s dataOld=ret.GetAt("data")
 
        s dataNew=##class(%ListOfDataTypes).%New()
        ;;;按id合并主题，再合并内容
        k idArr,idIndArr,subjectArr,subjectIndArr,dataArr,contentIndArr
        s len=dataOld.Count()
        f ind=1:1:len {
            s old=dataOld.GetAt(ind)
            s eduRecordId=old.GetAt("eduRecordId")
            s eduSubject=old.GetAt("eduSubject")
            s eduContent=old.GetAt("eduContent")
            continue:(eduRecordId="")||(eduSubject="")
            i ('$d(idArr(eduRecordId))) {
                s idInd=$o(idIndArr(""),-1)+1
                s idIndArr(idInd)=eduRecordId
                s idArr(eduRecordId)=idInd
                s dataArr(idInd)=old
            } else {
                s idInd=$g(idArr(eduRecordId))
            }
            i ('$d(subjectArr(eduRecordId,eduSubject))) {
                s subjectInd=$o(subjectIndArr(idInd,""),-1)+1
                s subjectIndArr(idInd,subjectInd)=eduSubject
                s subjectArr(eduRecordId,eduSubject)=subjectInd
            } else {
                s subjectInd=$g(subjectArr(eduRecordId,eduSubject))
            }
            s contentInd=$o(contentIndArr(idInd,subjectInd,""),-1)+1
            s contentIndArr(idInd,subjectInd,contentInd)=eduContent
        }
        ;;;option取值以类似javascript array的形式返回，而不是javascript object
        k optionIdArr
        //s options=##class(Nur.NIS.Service.Education2.HealthRecord).GetHealthEduItemOptions(wardId,hospitalId) 
        s options=##class(Nur.NIS.Service.Education2.HealthRecord).GetHealthEduItemOptions(wardId) 
        s len=options.Count()
        f ind=1:1:len {
            s option=options.GetAt(ind)
            s optionId=option.GetAt("id")
            continue:(optionId="")
            s optionIdArr(optionId)=""
        }
        s idInd="" f  s idInd=$o(idIndArr(idInd)) q:(idInd="")  d
        .s old=$g(dataArr(idInd))
        .s obj=##class(Nur.Tools).RapidSubset("eduRecordId^eduDateTime^nurseSign^taskId",old)
        .s subjectId=old.GetAt("subjectIds")
        .s subjectIds=##class(Nur.Tools).GetOptionsAsList(subjectId,",")
        .d obj.SetAt(subjectIds,"subjectIds")
        .s subjects=##class(%ListOfDataTypes).%New()
        .s subjectInd="" f  s subjectInd=$o(subjectIndArr(idInd,subjectInd)) q:(subjectInd="")  d
        ..s title=$g(subjectIndArr(idInd,subjectInd))
        ..s contents=##class(%ListOfDataTypes).%New()
        ..s subject=##class(Nur.Tools).RapidAssembly("title^content",title,contents)
        ..d subjects.Insert(subject)
        ..s contentInd="" f  s contentInd=$o(contentIndArr(idInd,subjectInd,contentInd)) q:(contentInd="")  d
        ...s content=$g(contentIndArr(idInd,subjectInd,contentInd))
        ...d contents.Insert(content)
        .d obj.SetAt(subjects,"subjects")
        .s options=##class(%ListOfDataTypes).%New()
        .s optionId="" f  s optionId=$o(optionIdArr(optionId)) q:(optionId="")  d
        ..s value=old.GetAt("option"_optionId)
        ..s option=##class(Nur.Tools).RapidAssembly("id^value",optionId,value)
        ..d options.Insert(option)
        .d obj.SetAt(options,"options")
        .s handlers=##class(%ListOfDataTypes).%New()
        .d handlers.Insert("undo") //撤销执行
        .d obj.SetAt(handlers,"handlers")
        .d dataNew.Insert(obj)
        s data=dataNew
    }
    q data
}

}
